package com.kaaction.modules.mer.api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.eb.entity.Customer;
import com.kaaction.modules.mer.entity.OrderSku;
import com.kaaction.modules.mer.entity.Sku;
import com.kaaction.modules.mer.service.OrderSkuService;
import com.kaaction.modules.mer.service.SkuService;

@Controller
@RequestMapping(value = "/api/v1/cart")
public class CartApiController extends BaseController {

	@Autowired
	private OrderSkuService orderSkuService;

	@Autowired
	private SkuService skuService;
	
	private final String IN_CART = "20";

	/**
	 * 获取某个人的购物车中的商品sku列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		logger.info("获取购物车中的商品列表");
		String openId = request.getParameter("openId");
		logger.info("openId = " + openId);
		OrderSku orderSku = new OrderSku();
		orderSku.setType(IN_CART);
		
		Customer customer = new Customer();
		customer.setThirdpartyId(openId);
		orderSku.setCustomer(customer);
		
		Page<OrderSku> orderSkuList = orderSkuService.findPage(new Page<OrderSku>(request, response), orderSku);
		super.writeAjaxResponse(response, orderSkuList);
	}
	
	@RequestMapping(value = "/updateAll")
	public void updateAll(HttpServletRequest request, HttpServletResponse response) {
		logger.info("更新购物车中的商品选择状态");
		String openId = request.getParameter("openId");
		String status = request.getParameter("status");
		if("1".equals(status))orderSkuService.updateAllStatus("checked",openId);
		else orderSkuService.updateAllStatus("",openId);
		
	}
	
	/**
	 * 更改购物车的商品数量/选中状态
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/update")
	public void update(HttpServletRequest request, HttpServletResponse response) {
		logger.info("更新购物车中的商品数量");
		String openId = request.getParameter("openId");
		String id = request.getParameter("skuId");
		String spuNumStr = request.getParameter("productNum");
		String eventValue = request.getParameter("event");
		logger.info("skuid=" + id + ",productNum = " + spuNumStr + ",event=" + eventValue);
		
		OrderSku orderSku = orderSkuService.findOrderSku(openId,id,IN_CART);
		if(orderSku != null){
			if(!StringUtils.isBlank(spuNumStr)) {
				int spuNum = Integer.parseInt(spuNumStr);
				orderSku.setSkuNum(spuNum);
			}
			if("toggleSelectStatus".equals(eventValue)){
				logger.info("当前操作是更改选中状态");
				String note = orderSku.getNote();
				logger.info("当前选中状态是"+note);
				if("".equals(note))note = "checked";
				else if("checked".equals(note))note = "";
				else note = "checked";
				logger.info("更改后状态是"+note);
				orderSku.setNote(note);
			}
			orderSkuService.save(orderSku);
			super.writeAjaxResponse(response, orderSku);
		} else {
			super.writeFailResponse(response, "", "没有找到对应的记录");
		}
		
	}
	
	/**
	 * shan
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/delete")
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		logger.info("清除一条购物车记录");
		String openId = request.getParameter("openId");
		String id = request.getParameter("skuId");
		logger.info("id=" + id);
		
		OrderSku orderSku = orderSkuService.findOrderSku(openId,id,IN_CART);
		if(orderSku != null){
			orderSkuService.delete(orderSku);
			super.writeAjaxResponse(response, "");
		} else {
			super.writeFailResponse(response, "", "没有找到对应的记录");
		}
		
		
	}

	/**
	 * 将商品加入到用户的待购列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/add")
	public void add(HttpServletRequest request, HttpServletResponse response) {
		logger.info("获取货物车中的商品列表");
		String openId = request.getParameter("openId");
		String spuId = request.getParameter("spuId");
		String spuNumStr = request.getParameter("productNum");
		String spuParams = request.getParameter("productSaleAttrSplitWithComma");
		String selectedColorId = "";
		String selectedSizeId = "";

		logger.info("============获取请求中的参数start=========");
		logger.info("openId = " + openId);
		logger.info("productId = " + spuId);
		logger.info("productNum = " + spuNumStr);
		logger.info("productParam = " + spuParams);
		logger.info("============获取请求中的参数end=========");

		if (!StringUtils.isBlank(spuParams) && spuParams.indexOf(",") > -1) {
			String[] params = spuParams.split(",");
			selectedColorId = params[0];
			selectedSizeId = params[1];
			Sku sku = skuService.findSku(spuId, selectedColorId, selectedSizeId);
			if (sku != null) {
				logger.info("找到对应的sku，id=" + sku.getId());
				int spuNum = 0;
				if (!StringUtils.isBlank(spuNumStr)) {
					spuNum = Integer.parseInt(spuNumStr);
				}
				OrderSku orderSku;
				OrderSku orderSkuInDb = orderSkuService.findOrderSku(openId,sku.getId(),IN_CART);
				if(orderSkuInDb != null){
					orderSkuInDb.setSkuNum(orderSkuInDb.getSkuNum() + spuNum);
					orderSku = orderSkuInDb;
					orderSkuService.save(orderSkuInDb);
				} else {
					Customer customer = new Customer();
					customer.setThirdpartyChannel("wechat");
					customer.setThirdpartyId(openId);

					orderSku = new OrderSku();
					orderSku.setCustomer(customer);
					orderSku.setSku(sku);
					orderSku.setSkuNum(spuNum);
					orderSku.setType(IN_CART);
					logger.info("准备往购物车增加一条记录:" + JSON.toJSONString(orderSku));
					orderSkuService.save(orderSku);
				}
				logger.info("添加到购物车成功...");
				super.writeAjaxResponse(response, orderSku);
			} else {
				logger.info("没有对应的商品");
				super.writeFailResponse(response, "", "没有对应的商品");
			}

		} else {
			logger.info("productParam参数不完整");
			super.writeFailResponse(response, "", "productSaleAttrSplitWithComma参数不完整，请提供颜色id和尺寸id，用逗号隔开");
		}
	}

}
